package com.felix.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * JacksonUtils
 *
 * @author xjh
 * @version 1.0
 * @date 2019-02-27
 */
public final class JacksonUtils {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * javaBean、列表数组转换为json字符串
     */
    public static String obj2json(Object obj) throws JsonProcessingException {
        return OBJECT_MAPPER.writeValueAsString(obj);
    }

    /**
     * 获取泛型的Collection Type
     *
     * @param collectionClass 泛型的Collection
     * @param elementClasses  元素类
     * @return JavaType Java类型
     * @since 1.0
     */
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return OBJECT_MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    /**
     * 与javaBean json数组字符串转换为列表
     */
    public static <T> List<T> json2list(String jsonArrayStr, Class<T> clazz) throws IOException {
        JavaType javaType = getCollectionType(ArrayList.class, clazz);
        return OBJECT_MAPPER.readValue(jsonArrayStr, javaType);
    }

}
